import React from "react";
import {
  Input,
  Select,
  Button,
  Spin,
  Modal,
  Space,
  Breadcrumb,
  Table,
  Tooltip,
  message,
  Popconfirm,
} from "antd";
import {
  EditFilled,
  DeleteFilled,
  CloudDownloadOutlined,
  DeliveredProcedureOutlined,
} from "@ant-design/icons";
import { Link } from "react-router-dom";

import moment from "moment";
import * as XLSX from "xlsx";
import ExportJsonExcel from "js-export-excel";
import {
  _addTch,
  _delTch,
  _delSomeTch,
  _getTchList,
  _updateTch,
  _selSingleTch,
} from "../../../../utils/user/index";
const { Option } = Select;
const { Search } = Input;
class NewsList extends React.Component {
  state = {
    selectedRowKeys: [], // Check here to configure the default column
    isLoading: false,

    e_visible: false,
    confirmLoading: false,
    tchList: null,
    tch_id: null,
    tch_name: null,
    tch_pwd: null,
    tch_title: null,
    tch_phone: null,
    tch_num: null,
    inputKey: Math.random(), //导入
  };
  getData = () => {
    this.setState({ isLoading: true });
    _getTchList()
      .then((res) => {
        if (res.status === 200 && res.data.code === 0) {
          // console.log(res.data.data);
          this.setState({ isLoading: false });
          const tchList = res.data.data;
          for (let i = 0; i < tchList.length; i++) {
            tchList[i].key = tchList[i].tch_id;
            // tchList[i].tch_name = tchList[i].tch_name;
            // tchList[i].tch_pwd = tchList[i].tch_pwd;
            // tchList[i].tch_title = tchList[i].tch_title;
            // tchList[i].tch_phone = tchList[i].tch_phone;
            tchList[i].control = tchList[i].tch_id;
          }
          this.setState({ tchList: tchList });
        }
      })
      .catch(() => {
        this.setState({ isLoading: false });
        message.error("服务器错误");
      });
  };
  selectOnSearch = (val) => {
    this.setState({ isLoading: true });
    _selSingleTch(val)
      .then((res) => {
        if (res.status === 200 && res.data.code === 0) {
          this.setState({ isLoading: false });
          if (res.data.data.length !== 0) {
            const tchList = res.data.data;
            for (let i = 0; i < tchList.length; i++) {
              tchList[i].key = tchList[i].tch_id;
              // tchList[i].tch_name = tchList[i].tch_name;
              // tchList[i].tch_pwd = tchList[i].tch_pwd;
              // tchList[i].tch_title = tchList[i].tch_title;
              // tchList[i].tch_phone = tchList[i].tch_phone;
              tchList[i].control = tchList[i].tch_id;
            }
            this.setState({ tchList: tchList });
          } else {
            message.info("抱歉查无此人");
          }
        }
      })
      .catch(() => {
        this.setState({ isLoading: false });
        message.error("服务器错误");
      });
  };
  componentDidMount = () => {
    this.getData();
  };
  editSource = (val) => {
    // console.log(val);

    this.setState({
      e_visible: true,
      tch_id: val.tch_id,
      tch_name: val.tch_name,
      tch_num: val.tch_num,
      tch_pwd: val.tch_pwd,
      tch_title: val.tch_title,
      tch_phone: val.tch_phone,
    });
  };
  editHandle = () => {
    let tempData = {
      tch_num: this.state.tch_num,
      tch_name: this.state.tch_name,
      tch_pwd: this.state.tch_pwd,
      tch_title: this.state.tch_title,
      tch_phone: this.state.tch_phone,
    };
    console.log(tempData);
    _updateTch(this.state.tch_id, tempData)
      .then((res) => {
        if (res.status === 200) {
          this.setState({
            e_visible: false,
          });
          message.success("修改成功");
          this.getData();
        }
      })
      .catch(() => {
        this.setState({ confirmLoading: false });
        message.error("服务器错误");
      });
  };
  deletSource = (val) => {
    if (this.state.selectedRowKeys.length) {
      let temp = {
        arr: this.state.selectedRowKeys,
      };
      _delSomeTch(temp)
        .then((res) => {
          console.log(res.data);
          if (res.status === 200 && res.data.code === 0) {
            if (res.data.data && res.data.data.code === -1) {
              message.warning(res.data.data.msg);
            } else {
              message.success("批量删除成功");
              this.getData();
            }
          }
        })
        .catch(() => {
          this.setState({ isLoading: false });
          message.error("服务器错误");
        });
    } else {
      _delTch(val)
        .then((res) => {
          console.log(res.data);
          if (res.status === 200 && res.data.code === 0) {
            if (res.data.data && res.data.data.code === -1) {
              message.warning(res.data.data.msg);
            } else {
              message.success("删除成功");
              this.getData();
            }
          }
        })
        .catch(() => {
          this.setState({ isLoading: false });
          message.error("服务器错误");
        });
    }
  };
  onSelectChange = (selectedRowKeys) => {
    console.log("selectedRowKeys changed: ", selectedRowKeys);
    this.setState({ selectedRowKeys });
  };
  handleCancel = () => {
    this.setState({
      e_visible: false,
      a_visible: false,
    });
  };
  onInputChange = (e) => {
    console.log(e.target.name);
    let inputValue = e.target.value;
    let inputName = e.target.name;
    this.setState({
      [inputName]: inputValue,
    });
  };
  onImportExcel = (file) => {
    this.setState({ isLoading: true });

    // 获取上传的文件对象
    const { files } = file.target;
    // 通过FileReader对象读取文件
    const fileReader = new FileReader();
    fileReader.onload = (event) => {
      try {
        const { result } = event.target;
        // 以二进制流方式读取得到整份excel表格对象
        const workbook = XLSX.read(result, {
          type: "binary",
        });
        // 存储获取到的数据
        let params = XLSX.utils.sheet_to_json(
          workbook.Sheets[workbook.SheetNames[0]]
        );
        let num_len = params[0].职工号.length;
        for (var i = 0; i < params.length; i++) {
          params[i].tch_name = params[i].姓名;
          delete params[i].姓名;
          params[i].tch_pwd = params[i].职工号.substring(num_len - 6);
          params[i].tch_num = params[i].职工号;
          delete params[i].职工号;
          params[i].tch_title = params[i].职称;
          delete params[i].职称;
          params[i].tch_phone = params[i].联系方式;
          delete params[i].联系方式;
        }
        let tempData = {
          data: params,
        };
        console.log(tempData);
        _addTch(tempData)
          .then((res) => {
            if (res.status === 200 && res.data.code === 0) {
              this.setState({ isLoading: false });

              message.success("数据导入成功！");
              this.getData();
            }
          })
          .catch(() => {
            this.setState({ isLoading: false });
            message.error("服务器错误");
          });
      } catch (e) {
        this.setState({ isLoading: false });
        message.error("文件类型不正确！");
      }
      this.setState({
        inputKey: Math.random(),
      });
    };
    // 以二进制方式打开文件
    fileReader.readAsBinaryString(files[0]);
  };

  //点击buttom触发input type="file"的点击事件
  uploadFile = () => {
    this.refs.inputFile.click();
  };
  selectOnChange = (value) => {
    this.setState({ tch_title: value });
  };

  //导出
  downloadFileToExcel = () => {
    let dataTable = []; //excel文件中的数据内容
    let option = {}; //option代表的就是excel文件
    let date = moment().format("YYYY-MM-DD");
    dataTable = this.state.tchList; //从props中获取数据源
    option.fileName = `${date}-教师用户文件`; //excel文件名称
    option.datas = [
      {
        sheetData: dataTable, //excel文件中的数据源
        sheetName: "教师", //excel文件中sheet页名称
        sheetFilter: [
          "tch_num",
          "tch_name",
          "tch_pwd",
          "tch_title",
          "tch_phone",
        ], //excel文件中需显示的列数据
        sheetHeader: ["职工号", "姓名", "密码", "职称", "联系方式", "备注"], //excel文件中每列的表头名称
      },
    ];
    let toExcel = new ExportJsonExcel(option); //生成excel文件
    toExcel.saveExcel(); //下载excel文件
  };
  render() {
    const columns = [
      {
        title: "职工号",
        dataIndex: "tch_num",
      },
      {
        title: "姓名",
        dataIndex: "tch_name",
      },
      {
        title: "密码",
        dataIndex: "tch_pwd",
      },
      {
        title: "职称",
        dataIndex: "tch_title",
      },
      {
        title: "联系方式",
        dataIndex: "tch_phone",
      },
      {
        title: "操作",
        dataIndex: "control",
        render: (text, record) => (
          <Space size="middle">
            <EditFilled
              onClick={this.editSource.bind(this, record)}
              style={{ color: "#95a5a6" }}
            />

            <Popconfirm
              title="确认要删除吗？"
              okText="是"
              cancelText="否"
              onConfirm={this.deletSource.bind(this, text)}
            >
              <DeleteFilled style={{ color: "#7f8c8d" }} />
            </Popconfirm>
          </Space>
        ),
      },
    ];

    const {selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <div>
        <div className="stu-header">
          <Breadcrumb style={{ margin: "16px 0" }}>
            <Breadcrumb.Item>
              <Link to="/admin/h">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item onClick={() => this.getData()}>
              教师管理
            </Breadcrumb.Item>
          </Breadcrumb>
          <Space size="large">
            <Search
              placeholder="输入职工号搜索"
              onSearch={this.selectOnSearch}
              enterButton
            />
            <Button
              icon={<CloudDownloadOutlined />}
              onClick={this.downloadFileToExcel}
              type="primary"
            >
              导出
            </Button>
            <Tooltip placement="topLeft" title="仅支持 .xlsx、.xls 格式的文件">
              <Button
                icon={<DeliveredProcedureOutlined />}
                onClick={this.uploadFile}
                type="primary"
              >
                导入
                <input
                  type="file"
                  key={this.state.inputKey}
                  accept=".xlsx, .xls"
                  onChange={this.onImportExcel}
                  hidden
                  ref="inputFile"
                />
              </Button>
            </Tooltip>
          </Space>
        </div>

        <div className="admin-body" style={{ padding: 15, minHeight: 360 }}>
          <Spin tip="Loading..." spinning={this.state.isLoading}>
            <Table
              columns={columns}
              dataSource={this.state.tchList}
              rowSelection={rowSelection}
              pagination={{ pageSize: 10 }}
              // scroll={{ y: 300 }}
            />
          </Spin>
          <Modal
            title="修改用户"
            visible={this.state.e_visible}
            onOk={this.editHandle}
            onCancel={this.handleCancel}
            okText={"确认"}
            width={300}
          >
            <Space direction="vertical">
              <Input
                addonBefore="职工号"
                name="tch_num"
                onChange={this.onInputChange}
                value={this.state.tch_num}
              />
              <Input
                addonBefore="姓名"
                name="tch_name"
                onChange={this.onInputChange}
                value={this.state.tch_name}
              />
              <Input
                addonBefore="密码"
                name="tch_pwd"
                onChange={this.onInputChange}
                value={this.state.tch_pwd}
              />
              <Input
                addonBefore="联系方式"
                name="tch_phone"
                onChange={this.onInputChange}
                value={this.state.tch_phone}
              />
              <Space>
                职称:
                <Select
                  showSearch
                  defaultValue={this.state.tch_title}
                  value={this.state.tch_title}
                  style={{ width: "180px" }}
                  placeholder="专业班级"
                  optionFilterProp="children"
                  onChange={this.selectOnChange}
                  filterOption={(input, option) =>
                    option.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                >
                  <Option value="教授">教授</Option>
                  <Option value="副教授">副教授</Option>
                  <Option value="讲师">讲师</Option>
                  <Option value="助教">助教</Option>
                </Select>
              </Space>
            </Space>
          </Modal>
        </div>
      </div>
    );
  }
}

export default NewsList;
